package com.crayon2f.test.xml;

import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.NodeList;
import org.xml.sax.InputSource;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import java.io.File;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.io.StringReader;
import java.net.URL;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.Arrays;

public class ShapeImageDownloader {
    
    // 数据库配置
    private static final String DB_URL = "jdbc:mysql://10.39.46.244:3306/basedata";
    private static final String DB_USER = "basedata_reader";
    private static final String DB_PASSWORD = "GFISAoTk3ZVuQV8b9CElBRS8";
    
    // 基础URL配置
    private static final String BASE_IMAGE_URL = "http://build-model.fnw.enncloud.cn/";
    
    // 本地存储根目录
    private static final String LOCAL_STORAGE_ROOT = "D:download/shape_images"; // 修改为你的本地存储路径
    
    public static void main(String[] args) {
        Connection conn = null;
        Statement stmt = null;
        ResultSet rs = null;
        
        try {
            // 1. 连接MySQL数据库
            conn = DriverManager.getConnection(DB_URL, DB_USER, DB_PASSWORD);
            stmt = conn.createStatement();
            
            // 2. 查询包含shape字段的表
            String sql = "SELECT name, shape FROM graphic_meta WHERE shape like '%image%'";
            rs = stmt.executeQuery(sql);
            
            // 3. 遍历结果集
            while (rs.next()) {
                String name = rs.getString("name");
                String shapeXml = rs.getString("shape");
                
                // 4. 解析name获取目录结构
                String[] nameParts = parseNameToPath(name);
                if (nameParts == null) continue;
                
                // 5. 解析XML获取image src
                String imageSrc = extractImageSrcFromXml(shapeXml);
                if (imageSrc == null || imageSrc.isEmpty()) continue;
                imageSrc = imageSrc.replaceAll("(\\s)+", "");
                // 6. 构建完整URL和本地路径
                String imageUrl = buildFullImageUrl(imageSrc);
                if (imageSrc.contains("https")) {
                    imageUrl = imageSrc;
                }
//                System.out.println(imageUrl);
                String localPath = buildLocalPath(nameParts, imageSrc);

                // 7. 下载图片
                downloadImage(imageUrl, localPath);
                
                System.out.println("下载成功: " + imageUrl + " -> " + localPath);
            }
            
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            // 关闭资源
            try { if (rs != null) rs.close(); } catch (SQLException e) { e.printStackTrace(); }
            try { if (stmt != null) stmt.close(); } catch (SQLException e) { e.printStackTrace(); }
            try { if (conn != null) conn.close(); } catch (SQLException e) { e.printStackTrace(); }
        }
    }
    
    /**
     * 解析name字段为目录结构
     * 示例: "mxGraph.变配电辅助设备.电流互感器" -> ["变配电辅助设备", "电流互感器"]
     */
    private static String[] parseNameToPath(String name) {
        if (name == null || !name.contains(".")) return null;
        
        String[] parts = name.split("\\.");
        if (parts.length < 3) return null;
        
        // 去掉第一个mxGraph部分
        return Arrays.copyOfRange(parts, 1, parts.length);
    }
    
    /**
     * 从XML中提取image标签的src属性
     */
    private static String extractImageSrcFromXml(String xml) {
        try {
            DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
            DocumentBuilder builder = factory.newDocumentBuilder();
            Document doc = builder.parse(new InputSource(new StringReader(xml)));
            
            NodeList imageNodes = doc.getElementsByTagName("image");
            if (imageNodes.getLength() == 0) return null;
            
            Element image = (Element) imageNodes.item(0);
            return image.getAttribute("src");
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
    }
    
    /**
     * 构建完整的图片URL
     */
    private static String buildFullImageUrl(String srcPath) {
        // 处理srcPath可能以/开头的情况
        String normalizedSrc = srcPath.startsWith("/") ? srcPath.substring(1) : srcPath;
        return BASE_IMAGE_URL + "/" + normalizedSrc;
    }
    
    /**
     * 构建本地存储路径
     */
    private static String buildLocalPath(String[] dirs, String srcPath) {
        // 创建本地目录结构
        File dir = new File(LOCAL_STORAGE_ROOT);
        for (String d : dirs) {
            dir = new File(dir, d);
        }
        
        // 确保目录存在
        if (!dir.exists()) {
            dir.mkdirs();
        }
        
        // 从srcPath中提取文件名
        String filename = srcPath.substring(srcPath.lastIndexOf('/') + 1);
        return new File(dir, filename).getAbsolutePath();
    }
    
    /**
     * 下载图片到本地
     */
    private static void downloadImage(String imageUrl, String localPath) {
        try (InputStream in = new URL(imageUrl).openStream();
             FileOutputStream out = new FileOutputStream(localPath)) {
            
            byte[] buffer = new byte[4096];
            int bytesRead;
            while ((bytesRead = in.read(buffer)) != -1) {
                out.write(buffer, 0, bytesRead);
            }
            
        } catch (Exception e) {
            System.err.println("下载失败: " + imageUrl);
            e.printStackTrace();
        }
    }
    
    // 静态初始化块加载MySQL驱动
    static {
        try {
            Class.forName("com.mysql.cj.jdbc.Driver");
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        }
    }
}